package com.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.nio.ByteBuffer;

/**
 * 处理服务器通道
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {//(1)
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//(2)

        // 以静默方式丢弃接收的数据((ByteBuf)msg).release();//(3)
        System.out.println("msg："+msg);
        ByteBuf in = (ByteBuf) msg;
        try {
            // (1)
            while (in.isReadable()) {
                System.out.println((char) in.readByte());
                System.out.flush();
            }
        } finally {
            // (2)
            ReferenceCountUtil.release(msg);
        }
        // 或者直接打印
        System.out.println("Yes, A new client in = " + ctx.name());

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {//(4)
        //出现异常时关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}
